<!--Note: The setcookie() function must appear BEFORE the <html> tag.-->
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
if (isset($_COOKIE[$cookie_name])) {
    $_COOKIE[$cookie_name] = $cookie_value;
} else {
    setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
}
//setcookie($cookie_name,$cookie_value,time() - (86400*30),"/");//Delete Cookies
// 86400 = 1 day
?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>PHP Cookies</title>
</head>
<body>
<h1>PHP Cookies</h1>

<div>
    <h3>Create Cookies With PHP</h3>
    <?php
    echo("Cookie is set");
    ?>
</div>
<div>
    <h3>Retrieve a Cookie Value</h3>
    <?php
    $userCookie = isset($_COOKIE[$cookie_name]) ? $_COOKIE[$cookie_name] : null;
    if ($userCookie != null) {
        echo("Cookie is named: " . $cookie_name . "<br>Value is: " . $userCookie);
    } else {
        echo "Cookie named '" . $cookie_name . "' does not exist!";
    }
    ?>
</div>
<div>
    <h3>Modify a Cookie Value</h3>
    <?php
    $cookie_value = "LALA";
    if (isset($_COOKIE[$cookie_name])) {
        $_COOKIE[$cookie_name] = $cookie_value;
    } else {
        setcookie($cookie_name, "New Value", time() + (86400 * 30), "/");
    }
    $userCookie = isset($_COOKIE[$cookie_name]) ? $_COOKIE[$cookie_name] : null;
    if ($userCookie != null) {
        echo("Cookie is named: " . $cookie_name . "<br>Value is: " . $userCookie);
    } else {
        echo "Cookie named '" . $cookie_name . "' does not exist!";
    }
    ?>
</div>
<div>
    <h3>Delete a Cookie</h3>
    <?php
    if (isset($_COOKIE[$cookie_name])) {
        unset($_COOKIE[$cookie_name]);
        $res = setcookie($cookie_name, null, time() - 3600, "/");
        if ($res) {
            echo "Cookie $cookie_name is deleted.";
        }
    }
    ?>
</div>
</body>
</html>